﻿using Server.DTool;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Server.Struct
{
    class Pool<Item> where Item : class
    {
        Stack<Item> _items;
        Func<Item> _creater;

        public event Action<Item> BeforeTake;
        public event Action<Item> BeforeRecycle;

        public Pool(Func<Item> creater)
        {
            _items = new Stack<Item>();
            SetCreater(creater);
        }

        public void SetCreater(Func<Item> creater)
        {
            _creater = creater;
        }

        public virtual Item Take()
        {
            Item item;
            if (_items.Count < 1)
            {
                item = _creater();
                _items.Push(item);
            }
            item = _items.Pop();
            BeforeTake?.Invoke(item);
            return item;
        }

        public virtual void Recycle(Item t)
        {
            BeforeRecycle?.Invoke(t);
            _items.Push(t);
        }
    }
}
